package controller;

import Data.File;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import util.TreeViewIterator;
import util.UpdateAbsolutePath;

import java.util.Map;

import java.io.IOException;

import static controller.MainController.*;
import static operations.renameOperations.isAbleToRename;
import static util.FileRW.writeDisk;
import static util.GetFileAbsolutePath.getAbsPath;


public class RenameController {
    @FXML
    private Button renameCancelButton;

    @FXML
    private Button renameConfirmButton;

    @FXML
    private TextField renameField;

    private static TreeView<String> tmpFileView;
    private static TextField tmpPathText;

    @FXML
    void initialize() {
        renameField.setText(currentFile.getFileName());
    }

    @FXML
    void renameCancel(ActionEvent event) {
        Stage stage = (Stage) renameField.getScene().getWindow();
        stage.close();
    }

    @FXML
    void renameConfirm(ActionEvent event) throws IOException, ClassNotFoundException {
        if (isAbleToRename(currentFile, renameField.getText())) {
            currentFile.setFileName(renameField.getText());
            UpdateAbsolutePath.updateChildrenPath(currentFile);
            icons.get(currentFile).setText(currentFile.getFileName());
            if (currentFile.getParent() == rootFile) {
                currentFile = rootFile;
            } else {
                currentFile = currentFile.getParent();
            }
            recentNode = treeMap.get(currentFile);
            TreeViewIterator treeViewIterator = new TreeViewIterator();
            treeViewIterator.Clear();
            treeViewIterator.iterator(tmpFileView);
            Stage stage = (Stage) renameField.getScene().getWindow();
            stage.close();
            writeDisk();
        } else {
            AnchorPane anchorPane = new AnchorPane();
            Scene scene = new Scene(anchorPane, 200, 20);
            Label label = new Label("文件不能重名！");
            label.setLayoutX(65);
            label.setLayoutY(5);
            anchorPane.getChildren().add(label);
            Stage stage = new Stage();
            stage.setScene(scene);
            stage.setTitle("错误");
            stage.setResizable(false);
            stage.show();
        }
    }

    public static void sentParam(TreeView<String> fileView, TextField pathText){
        tmpFileView = fileView;
        tmpPathText = pathText;
    }
}
